
package com.example.filtransfer.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileVersionUtil {
    private static final String FILENAME = ".data";

    public String getVersion() throws IOException {
        String version = null;
        File file = new File(FILENAME);
        if (file.exists() && file.isFile()) {
            Scanner scanner = null;
            try {
                scanner = new Scanner(new FileInputStream(file));
                version = scanner.next();
                try {
                    Long.parseLong(version);
                } catch (NumberFormatException e) {
                    version = null;
                }
            } finally {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
        return version;
    }

    public String writeVerion(String version) throws IOException {
        File file = new File(FILENAME);
        FileWriter fileWriter = null;
        if (version == null) {
            version = Long.toString(System.currentTimeMillis());
        }
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write(version);
            fileWriter.close();
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
        return version;
    }
}
